package com.hy.admin.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class TestOauth {
	public static void main(String[] args) {
		try {
			// 创建Httpclient对象
			CloseableHttpClient httpclient = HttpClients.createDefault();

			// 创建http POST请求
			HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/admin-web/oauth/token");

			// 设置2个post参数，一个是scope、一个是q
			List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
			parameters.add(new BasicNameValuePair("client_id", "mobile-client"));
			parameters.add(new BasicNameValuePair("client_secret", "mobile"));
			parameters.add(new BasicNameValuePair("grant_type", "password"));
			
			parameters.add(new BasicNameValuePair("username", "15011037312"));
			parameters.add(new BasicNameValuePair("password", "aaaaa1"));
			
			// 构造一个form表单式的实体
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
			// 将请求实体设置到httpPost对象中
			httpPost.setEntity(formEntity);
//			httpPost.addHeader("Content-Type", "application/json");

			CloseableHttpResponse response = null;
			try {
			    // 执行请求
			    response = httpclient.execute(httpPost);
			    System.out.println(response);
			    // 判断返回状态是否为200
			    if (response.getStatusLine().getStatusCode() == 200) {
			        String content = EntityUtils.toString(response.getEntity(), "UTF-8");
			        System.out.println(content);
			    }
			} finally {
			    if (response != null) {
			        response.close();
			    }
			    httpclient.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
